package com.jakesepicstuff.jnotepad;

import javax.swing.*;
import java.io.*;

public class OpenFile {
	
	String fileName;
	JFileChooser fileChooser = new JFileChooser();
	
	//CONSTRUCTOR
	public OpenFile() {
		
		int returnVal = fileChooser.showOpenDialog(null);
		fileName = fileChooser.getName(fileChooser.getSelectedFile());
		
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			
			File file = fileChooser.getSelectedFile();
			openTheFile(file);
			System.out.printf("%s has been opened", fileName);
		}
	}
	
	// OPEN FILE
	public void openTheFile(File file) {
		
		FileReader fr;
		BufferedReader br;
		
		try {
			
			fr = new FileReader(file);
			br = new BufferedReader(fr);
			
			String line = "";
			
			while (line != null) {
				
				try {
					
					line = br.readLine();
					Display.textArea.append(line);
					Display.textArea.append("\n");
					
				} catch (IOException e) {
					
					JOptionPane.showMessageDialog(null, "Error opening the file");
					e.printStackTrace();
				}
				
			}
		} catch (FileNotFoundException e) {
			
			JOptionPane.showMessageDialog(null, file + " not found!");
			e.printStackTrace();
		}
		
		
	}
}